function [mi, ms] = minpos(varargin)
% minpos  - return not the min but only the pos
%
% FORMAT:       [mi, ms] = minpos(x [, y, dim])
%
% Input fields:
%
%       x       vector or array
%       y       if given and not empty must match x in type and size
%       dim     dimension to work along if y is empty
%
% Output fields:
%
%       mi      minimum index
%       ms      minimum subscript (cell array)
%
% Note: uses the internal min() function of Matlab.

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% no argument check, simply pass on
try
    [mi{1:2}] = min(varargin{:});
    mi = mi{2};
catch
    rethrow(lasterror);
end

if nargout > 1
    sz = size(varargin{1});
    if nargin > 2
        dim = varargin{3};
    elseif sz(1) > 1
        dim = 1;
    else
        dim = findfirst(sz > 1);
    end
    if dim > 1
        mi = 1 + (mi - 1) .* prod(sz(1:dim-1));
    end
    [ms{1:ndims(varargin{1})}] = ind2sub(sz, mi);
    if numel(mi) > 1
        sz(dim) = 1;
        for c = setdiff(1:ndims(varargin{1}), dim)
            rm = sz;
            rm([c, dim]) = 1;
            ms{c} = repmat(reshape(1:sz(c), ...
                [ones(1, c - 1), sz(c), ones(1, numel(sz) - c)]), rm);
        end
    end
end
